import os
import asyncio
import json
from datetime import datetime, date, time
from typing import Optional
from fastapi import APIRouter, Query, Request, Depends
from fastapi.templating import Jinja2Templates
from collections import defaultdict
from fastapi import APIRouter, WebSocket, WebSocketDisconnect
from websockets.exceptions import ConnectionClosedOK, ConnectionClosedError

from backend.api.v1.ws import generate_data
from backend.config.config import settings          
from backend.common.jwt import get_current_active_user
from backend.models.user import User



router = APIRouter()


templates = Jinja2Templates(directory=os.path.join(settings.PROJECT_PATH, "templates"))

@router.get("/dashboard")
async def root(request: Request):
    return templates.TemplateResponse("index.html", {"request": request, "ws_host": settings.WEB_HOST, "ws_port": settings.WEB_PORT})


# @router.get("/data")
# async def get_data(current_user: User = Depends(get_current_active_user)):
#     """
#     Get current RPA task data
#     """
#     # Use the same mock data generation function as WebSocket
#     # This ensures we're using the same current data without accumulation
#     data = await generate_data()
#     return data


# @router.get("/summary")
# async def get_summary(current_user: User = Depends(get_current_active_user)):
#     """
#     Get summary of RPA tasks
#     """
#     # 修复KeyError: 'summary'错误
#     # 返回空字典或者生成一个有效的摘要数据
#     return {"success_count": 0, "failed_count": 0, "total_count": 0, "success_rate": 0}


@router.get("/tasks")
async def get_tasks(
    current_user: User = Depends(get_current_active_user),
    status: Optional[str] = None,
    start_date: Optional[str] = None,
    end_date: Optional[str] = None
):
    """
    Get RPA tasks with optional filters
    """
    query = JobRecords.all()
    
    if status:
        query = query.filter(result_status=status)
    
    if start_date:
        try:
            # 检查是否已包含时间部分
            if " " in start_date and len(start_date) > 10:
                # 日期字符串已包含时间部分，直接解析
                start_datetime = datetime.strptime(start_date, "%Y-%m-%d %H:%M:%S")
            else:
                # 仅包含日期，添加默认的开始时间 00:00:00
                start_datetime = datetime.strptime(f"{start_date} 00:00:00", "%Y-%m-%d %H:%M:%S")
            query = query.filter(exec_start_time__gte=start_datetime)
        except (ValueError, TypeError) as e:
            print(f"仪表盘日期解析错误(start_date): {e}")
    
    if end_date:
        try:
            # 检查是否已包含时间部分
            if " " in end_date and len(end_date) > 10:
                # 日期字符串已包含时间部分，直接解析
                end_datetime = datetime.strptime(end_date, "%Y-%m-%d %H:%M:%S")
            else:
                # 仅包含日期，添加默认的结束时间 23:59:59
                end_datetime = datetime.strptime(f"{end_date} 23:59:59", "%Y-%m-%d %H:%M:%S")
            query = query.filter(exec_end_time__lte=end_datetime)
        except (ValueError, TypeError) as e:
            print(f"仪表盘日期解析错误(end_date): {e}")
    
    tasks = await query.values(
        "app_name", "result_status", "exec_start_time", "exec_end_time", "exec_duration", "result_detail"
    )
    
    return {"tasks": list(tasks)}



@router.get("/monthly-stats")
async def get_monthly_stats(
    current_user: User = Depends(get_current_active_user),
    month: Optional[str] = None,
    start_date: Optional[str] = None,
    end_date: Optional[str] = None
):
    # 查询在时间范围内的所有记录
    records = await JobRecords.filter(
        start_date__gte=start_date,
        start_date__lte=end_date,
    ).all()

    # 以 app_name 分类统计
    stats = defaultdict(lambda: {"success": 0, "failed": 0})

    for record in records:
        if not record.start_date or not record.app_name:
            continue
        key = record.app_name

        if record.result_status == ResultStatusEnum.success:
            stats[key]["success"] += 1
        elif record.result_status == ResultStatusEnum.failed:
            stats[key]["failed"] += 1

    # 组织结果列表
    result = []
    for app_name, data in stats.items():
        success = data["success"]
        failed = data["failed"]
        total = success + failed
        success_rate = round((success / total) * 100, 2)
        result.append({
            "rpa_name": app_name,
            "success_count": success,
            "failed_count": failed,
            "total_count": total,
            "success_rate": success_rate
        })
    if not month:
        current_date = datetime.now()
        month = current_date.strftime("%Y-%m")

    return {
        "month": month,
        "stats": result
    }